package ch.il07.utils.logging.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import ch.il07.utils.ConverterProperties;
import ch.il07.utils.logging.ChainLogger;
import ch.il07.utils.logging.Level;
import ch.il07.utils.logging.LoggerException;

/**
 * This Class Handles the Exception logging in terms of file logging
 */
public class FileLogger extends ChainLogger {

	private FileWriter fileWriter;

	public FileLogger() {
		super(Level.getLevelByName(ConverterProperties
				.getProperty("logger.file.level")));
		initWriter();
	}

	private void initWriter() {
		String filename = getFilename();
		try {
			fileWriter = new FileWriter(filename, true);
		} catch (IOException e) {
			throw new LoggerException(e);
		}
	}

	private String getFilename() {
		String directoryName = ConverterProperties.getProperty("logger.file.filename");
		if(directoryName == null || !new File(directoryName).exists()) {
			directoryName = System.getProperty("java.io.tmpdir");
		}
		if(!new File(directoryName).canWrite()) {
			throw new LoggerException("logger must be able to write to ["+directoryName+"]");
		}
		StringBuilder sb = new StringBuilder(directoryName);
		sb.append(System.getProperty("file.separator"));
		sb.append("converter_");
		sb.append(getDateTime("yyyy-MM-dd_HH:mm:ss"));
		sb.append(".log");
		return sb.toString();
	}

	@Override
	protected void writeLog(Level level, String msg, Throwable cause) {
		try {
			fileWriter.append(format(level, msg, cause));
			fileWriter.flush();
		} catch (IOException e) {
			throw new LoggerException(e);
		}
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		if (fileWriter != null) {
			fileWriter.close();
		}
	}

}
